#!/bin/bash

# YxYWeb Docker一键部署脚本
# 作者: YxYWeb Team
# 版本: 1.0.0

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置变量
IMAGE_NAME="yxyweb"
IMAGE_TAG="latest"
CONTAINER_NAME="yxyweb-app"
IMAGE_FILE="yxyweb-image.tar.gz"
COMPOSE_FILE="docker-compose.production.yml"
ENV_FILE=".env"
PORT="8000"

# 打印带颜色的消息
print_message() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# 检查Docker环境
check_docker() {
    print_step "检查Docker环境..."
    
    if ! command -v docker &> /dev/null; then
        print_error "Docker未安装，请先安装Docker"
        exit 1
    fi
    
    if ! docker info &> /dev/null; then
        print_error "Docker服务未启动，请启动Docker服务"
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null; then
        print_error "Docker Compose未安装，请先安装Docker Compose"
        exit 1
    fi
    
    print_message "Docker环境检查通过"
}

# 检查镜像文件
check_image_file() {
    print_step "检查镜像文件..."
    
    if [[ ! -f "$IMAGE_FILE" ]]; then
        print_error "镜像文件不存在: $IMAGE_FILE"
        print_message "请确保镜像文件在当前目录下"
        exit 1
    fi
    
    print_message "镜像文件检查通过: $IMAGE_FILE"
}

# 导入镜像
import_image() {
    print_step "导入Docker镜像..."
    
    print_message "正在导入镜像，请稍候..."
    
    if docker load < "$IMAGE_FILE"; then
        print_message "镜像导入成功"
        
        # 验证镜像
        if docker images | grep -E "^$IMAGE_NAME[[:space:]]+$IMAGE_TAG[[:space:]]" > /dev/null; then
            print_message "镜像验证成功"
        else
            print_error "镜像验证失败"
            exit 1
        fi
    else
        print_error "镜像导入失败"
        exit 1
    fi
}

# 创建环境配置文件
create_env_file() {
    print_step "检查配置..."
    
    print_message "应用使用默认配置，无需创建.env文件"
    print_message "如需修改配置，请编辑 config/settings.py 文件"
    print_message ""
    print_message "需要修改的配置项："
    print_message "- DB_PASSWORD: 数据库密码"
    print_message "- DB_HOST: 数据库主机地址"
    print_message "- AI_USERNAME: AI服务用户名"
    print_message "- AI_PASSWORD: AI服务密码"
    print_message ""
    print_message "修改方法："
    print_message "1. 编辑 config/settings.py 文件"
    print_message "2. 重新构建镜像"
    print_message "3. 重新部署应用"
}

# 检查端口占用
check_port() {
    print_step "检查端口占用..."
    
    if netstat -tuln | grep -q ":$PORT "; then
        print_warning "端口 $PORT 已被占用"
        read -p "是否继续部署? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            print_message "部署已取消"
            exit 0
        fi
    else
        print_message "端口 $PORT 可用"
    fi
}

# 停止现有容器
stop_existing_container() {
    print_step "停止现有容器..."
    
    if docker ps -a | grep -q "$CONTAINER_NAME"; then
        print_message "发现现有容器，正在停止..."
        docker stop "$CONTAINER_NAME" 2>/dev/null || true
        docker rm "$CONTAINER_NAME" 2>/dev/null || true
        print_message "现有容器已清理"
    else
        print_message "未发现现有容器"
    fi
}

# 启动应用
start_application() {
    print_step "启动应用..."
    
    # 检查docker-compose文件
    if [[ ! -f "$COMPOSE_FILE" ]]; then
        print_error "Docker Compose文件不存在: $COMPOSE_FILE"
        exit 1
    fi
    
    # 检查镜像是否存在
    if ! docker images | grep -E "^$IMAGE_NAME[[:space:]]+$IMAGE_TAG[[:space:]]" > /dev/null; then
        print_error "镜像不存在: $IMAGE_NAME:$IMAGE_TAG"
        print_message "请先导入镜像: docker load < $IMAGE_FILE"
        exit 1
    fi
    
    print_message "使用Docker Compose启动应用..."
    
    if docker-compose -f "$COMPOSE_FILE" up -d; then
        print_message "应用启动成功"
    else
        print_error "应用启动失败"
        exit 1
    fi
}

# 验证部署
verify_deployment() {
    print_step "验证部署..."
    
    # 等待应用启动
    print_message "等待应用启动..."
    sleep 30
    
    # 检查容器状态
    if docker ps | grep -q "$CONTAINER_NAME"; then
        print_message "容器运行正常"
    else
        print_error "容器未正常运行"
        docker logs "$CONTAINER_NAME" 2>/dev/null || true
        exit 1
    fi
    
    # 检查应用健康状态
    print_message "检查应用健康状态..."
    if curl -f http://localhost:$PORT/health &>/dev/null; then
        print_message "应用健康检查通过"
    else
        print_warning "应用健康检查失败，但容器运行正常"
        print_message "请检查应用日志: docker logs $CONTAINER_NAME"
    fi
    
    # 显示访问信息
    echo ""
    echo "=========================================="
    print_message "部署完成！"
    echo "=========================================="
    echo ""
    print_message "应用访问地址: http://localhost:$PORT"
    print_message "容器名称: $CONTAINER_NAME"
    echo ""
    print_message "常用命令："
    print_message "- 查看日志: docker logs -f $CONTAINER_NAME"
    print_message "- 停止应用: docker-compose -f $COMPOSE_FILE down"
    print_message "- 重启应用: docker-compose -f $COMPOSE_FILE restart"
    print_message "- 进入容器: docker exec -it $CONTAINER_NAME bash"
    echo ""
}

# 显示帮助信息
show_help() {
    echo "YxYWeb Docker一键部署脚本"
    echo ""
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  --help, -h          显示帮助信息"
    echo "  --skip-import       跳过镜像导入"
    echo "  --skip-env          跳过环境配置"
    echo "  --port PORT         指定端口 (默认: 8000)"
    echo "  --image FILE        指定镜像文件 (默认: yxyweb-image.tar.gz)"
    echo ""
    echo "示例:"
    echo "  $0                    # 完整部署"
    echo "  $0 --skip-import      # 跳过镜像导入"
    echo "  $0 --port 8080        # 使用8080端口"
    echo ""
}

# 主函数
main() {
    echo "=========================================="
    echo "    YxYWeb Docker一键部署工具"
    echo "=========================================="
    echo ""
    
    # 解析参数
    SKIP_IMPORT=false
    SKIP_ENV=false
    
    while [[ $# -gt 0 ]]; do
        case $1 in
            --help|-h)
                show_help
                exit 0
                ;;
            --skip-import)
                SKIP_IMPORT=true
                shift
                ;;
            --skip-env)
                SKIP_ENV=true
                shift
                ;;
            --port)
                PORT="$2"
                shift 2
                ;;
            --image)
                IMAGE_FILE="$2"
                shift 2
                ;;
            *)
                print_error "未知参数: $1"
                exit 1
                ;;
        esac
    done
    
    # 执行部署流程
    check_docker
    check_port
    
    if [[ "$SKIP_IMPORT" == "false" ]]; then
        check_image_file
        import_image
    else
        print_warning "跳过镜像导入"
    fi
    
    if [[ "$SKIP_ENV" == "false" ]]; then
        create_env_file
    else
        print_warning "跳过环境配置"
    fi
    
    stop_existing_container
    start_application
    verify_deployment
}

# 执行主函数
main "$@" 